<template>
  <div id="bg">
    <a-row type="flex" justify="center" align="middle" style="min-height: 100vh;">
      <!-- 左侧图片 -->
      <a-col :span="16" style="text-align: right;">
        <!--<img src="../assets/img/bg.png" style="width: 100%; height: 500px;border-radius: 25px;">-->
      </a-col>

      <!-- 右侧卡片 -->
      <a-col :span="7" style="text-align: left;">
        <a-card style="width: 100%; height: 100%;">
          <a-tabs v-model:activeKey="activeTab">
            <a-tab-pane key="login" tab="登录">
              <a-form @submit.prevent="handleLogin" :model="loginForm">
                <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名!' }]">
                  <a-input v-model:value="loginForm.username" />
                </a-form-item>
                <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
                  <a-input type="password" v-model:value="loginForm.password" />
                </a-form-item>
                <a-form-item style="text-align: center;">
                  <a-button type="primary" html-type="submit" style="width: 100px;">登录</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
            <a-tab-pane key="register" tab="注册">
              <a-form @submit.prevent="handleRegister" :model="registerForm">
                <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名!' }]">
                  <a-input v-model:value="registerForm.username" />
                </a-form-item>
                <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
                  <a-input type="password" v-model:value="registerForm.password" />
                </a-form-item>
                <a-form-item label="确认密码" name="confirmPassword"
                  :rules="[{ required: true, message: '请再次输入密码!' }, { validator: validateConfirmPassword }]">
                  <a-input type="password" v-model:value="registerForm.confirmPassword" />
                </a-form-item>
                <a-form-item label="邮箱" name="email"
                  :rules="[{ required: true, message: '请输入邮箱!' }, { type: 'email', message: '请输入正确的邮箱格式!' }]">
                  <a-input v-model:value="registerForm.email" :validate-status="emailStatus" :help="emailHelp" />
                </a-form-item>
                <a-form-item style="text-align: center;">
                  <a-button type="primary" html-type="submit" style="width: 100px;">注册</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';

const router = useRouter();

const activeTab = ref('login');

const loginForm = ref({
  username: '',
  password: '',
});

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
});

const emailStatus = ref('');
const emailHelp = ref('');

const validateConfirmPassword = async (rule, value) => {
  if (value !== registerForm.value.password) {
    return Promise.reject('两次输入的密码不一致!');
  }
  return Promise.resolve();
};

const handleLogin = () => {
  fetch('/api/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username: loginForm.value.username, password: loginForm.value.password })
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`Network response was not ok ${response.statusText}`);
      }
      return response.json();
    })
    .then(data => {
      console.log('Login successful:', data);
      message.success('登录成功！');
      // 存储token并处理登录成功的逻辑
      localStorage.setItem('username', data.username);
      localStorage.setItem('token', data.token);
      // 跳转到其他页面
      setTimeout(() => {
        window.location.href = '/space';
      }, 2000);
      // router.push('/space');
    })
    .catch(error => {
      console.error('Login failed:', error);
      // 处理登录失败
      message.error('登录失败!');
      // 清除登录表单
      loginForm.value = {
        username: '',
        password: '',
      };
    });
};


const handleRegister = () => {
  fetch('/api/register', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username: registerForm.value.username, password: registerForm.value.password, email: registerForm.value.email })
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`Network response was not ok ${response.statusText}`);
      }
      return response.json();
    })
    .then(data => {
      console.log('Registration successful:', data);
      // 弹窗提示注册成功
      message.success('注册成功！');
      // 重置注册表单
      registerForm.value = {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
      };
      setTimeout(() => {
        activeTab.value = 'login';
      }, 2000);
      //window.location.href = '/login';
      //router.push('/login');
    })
    .catch(error => {
      console.error('Registration failed:', error);
      // 弹窗提示注册失败
      message.error('注册失败!');
      // 重置注册表单
      registerForm.value = {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
      };
    });
};
</script>

<style scoped>
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  /* 或者根据需要设置为auto */
}

/*背景图片*/
#bg {
  background-image: url('../assets/img/bg.png');
  background-position: center;
  /* 水平居中 */
  background-repeat: no-repeat;
  /* 不重复 */
  /*background-attachment: fixed;  固定背景图片位置 */
  background-size: cover;
  /* 覆盖整个容器 */
}

.ant-card {
  width: 300px;
  border-radius: 20px;
}

.ant-col {
  margin: 10px;
}

/* 登录注册窗口内的表单和按钮样式 */
.ant-form-item-control-input-content {
  text-align: center;
}

.ant-card{
  backdrop-filter:blur(8px);
  background-color:rgba(255,255,255,0.6)
}
</style>
